# browser_ops.py
import asyncio
import os
from pyppeteer import launch
from logger_config import logger
from config import get_env
from utils import save_cookie


async def launch_browser():
    """启动浏览器并返回实例"""
    browser = await launch({
        "headless": False,
        "autoClose": False,
        "args": [
            "--start-maximized",
            "--no-sandbox",
            "--disable-setuid-sandbox",
            "--disable-infobars",
            "--ignore-certificate-errors",
            "--log-level=3",
            "--disable-extensions",
            f"--user-agent={get_env('USERAGENT')}",
            "--disable-dev-shm-usage",
        ],
        "ignoreHTTPSErrors": True,
        "handleSIGINT": False,
        "handleSIGTERM": False,
        "handleSIGHUP": False,
    })
    return browser


async def login(browser):
    """登录目标网站"""
    logger.info("开始登录网站...")

    homepage = await browser.newPage()
    await homepage.evaluateOnNewDocument('''() => {
        Object.defineProperty(navigator, 'webdriver', {
            get: () => undefined
        })
    }''')
    await homepage.setViewport({'width': 1200, 'height': 800})
    await homepage.setUserAgent(get_env('USERAGENT'))

    # 导航到登录页面
    await homepage.goto(get_env('HOST_URL'), options={'timeout': 15000})
    logger.success("成功访问网站首页")

    # 输入凭据并登录
    await homepage.type("#form > div > div.user > input", get_env('USER_NAME'))
    await homepage.type("#form > div > div.pwd > input", get_env('USER_PASSWORD'))
    await homepage.click("#form > div > div.right > input")

    # 等待登录完成
    await asyncio.sleep(3)
    logger.success("登录成功")

    # 保存cookies
    cookie_after_login = await homepage.cookies()
    await save_cookie(cookie_after_login)
    logger.info("Cookies已保存")

    # 关闭登录页面
    await homepage.close()


async def fetch_page_with_browser(browser, url):
    """使用浏览器获取页面内容（适用于需要JS分析的页面）"""
    logger.info(f"使用浏览器访问: {url}")

    try:
        page = await browser.newPage()
        await page.setUserAgent(get_env('USERAGENT'))
        await page.goto(url, options={'timeout': 15000})
        content = await page.content()
        logger.success(f"成功获取页面内容，长度: {len(content)}")
        return content
    except Exception as e:
        logger.error(f"浏览器获取页面失败: {str(e)}")
        return None
    finally:
        if 'page' in locals() and not page.isClosed():
            await page.close()